const Goodtype = require('../db.js').Goodtype;
const Good = require('../db.js').Good;
//下面这两个包用来生成时间
const moment = require('moment');
const objectIdToTimestamp = require('objectid-to-timestamp');
//用于密码加密
const sha1 = require('sha1');
//createToken
const createToken = require('../token/createToken.js');

//图片上传
const { uploadFile } = require('../util/upload')
const path = require('path')
//数据库的操作

const findtype = (name) => {
    return new Promise((resolve, reject) => {
        Goodtype.findOne({ typename:name }, (err, doc) => {
            if(err){
                reject(err);
            }
            resolve(doc);
        });
    });
};

//添加类别
const addgtype = async ( ctx ) => {
    let goodtype = new Goodtype({
        typename: ctx.request.body.typename,
    });
    
    //将objectid转换为用户创建时间(可以不用)
    //goodtype.create_time = moment(objectIdToTimestamp(goodtype._id)).format('YYYY-MM-DD HH:mm:ss');

    let doc = await findtype(goodtype.typename);
    if(doc){ 
        ctx.status = 200;
        ctx.body = {
            status: 'fail',
            message:'类别已经存在已经存在'
        };
    }else{
        await new Promise((resolve, reject) => {
            goodtype.save((err) => {
                if(err){
                    reject(err);
                }
                resolve();
            });
        });
        ctx.status = 200;
        ctx.body = {
            status: "success",
            message:'商品类别添加成功'
        }
    }
};

//获得所有商品类别
const getgoodtypes = async( ctx ) => {
    //查询所有用户信息
    let doc = await findAllGtype();
    ctx.status = 200;
    ctx.body = {
        status: 'success',
        result: doc
    };
};
//找到所有商品类别
const findAllGtype = () => {
    return new Promise((resolve, reject) => {
        Goodtype.find({}, (err, doc) => {
            if(err){
                reject(err);
            }
            resolve(doc);
        });
    });
};
//添加类别
const addgood = async ( ctx ) => {
    let good = new Good({
        goodname: ctx.request.body.name,
        goodprice: ctx.request.body.price,
        goodtype: ctx.request.body.type,
        ishot: ctx.request.body.delivery,
        img:ctx.request.body.imgurl
    });
    await new Promise((resolve, reject) => {
        good.save((err) => {
            if(err){
                reject(err);
            }
            resolve();
        });
    });
    ctx.status = 200;
    ctx.body = {
        status: "success",
        message:'商品添加成功'
    }
    
};
//上传图片
const upload = async (ctx) => {
    // 上传文件请求处理
    let result = { success: false }
    let serverFilePath = path.join( __dirname, '..', 'static' )

    // 上传文件事件
    result = await uploadFile( ctx, {
      path: serverFilePath
    })

    ctx.body = result
}

const findAllgGoods = (params) => {

    // pagesize = params.pagesize || 5;
    // n = params.currentpage || 1
    // let query = new Promise((resolve,reject) => {
    //     Good.find({}, (err, doc) => {
    //         if(err){
    //             reject(err);
    //         }
    //         resolve(doc);
    //     });
    // })    

    // Good.count().exec((err,count) => {
    //     //Math.ceil(0.33) 1 向上取整
    //     let pages = Math.ceil(count/pagesize)
    //     if(n > pages){
    //         callback('',{"data":''});
    //         return;
    //     }
    //     query.skip(pagesize*(n-1)).limit(pagesize).exec('find', (err,result) => {
    //         return result
    //     });
    // })

    return new Promise((resolve, reject) => {
        Good.find({}, (err, doc) => {
            if(err){
                reject(err);
            }
            resolve(doc);
        });
    });
};
const findtypesid = (id) => {
    return new Promise((resolve, reject) => {
        Goodtype.findOne({_id:id}, (err, doc) => {
            if(err){
                reject(err);
            }
            resolve(doc);
        });
    });
};

//找到所有商品
const getallgoods = async( ctx ) => {
    let params = {
        pagesize: ctx.request.body.pagesize,
        currentpage: ctx.request.body.currentpage,
    };
    console.log(params)
    let doc = await findAllgGoods(params);
    for(let i in doc){
        if(doc[i].goodtype){
            let typearr = []
            for(let item of doc[i].goodtype){
                let typeobj = await findtypesid(item)
                typearr.push(typeobj.typename)
            }
            doc[i].goodtype = typearr
        }
        
    }
    ctx.status = 200;
    ctx.body = {
        status: "success",
        data: doc
    };
};
//获取单个商品信息
const getgoodinfo = async( ctx ) => {
    let id = ctx.request.body._id
    let doc = await new Promise((resolve, reject) => {
        Good.findOne({_id:id}, (err, doc) => {
            if(err){
                reject(err);
            }
            resolve(doc);
        });
    });
    ctx.status = 200;
    ctx.body = {
        status: "success",
        data: doc
    };
   
};

module.exports = {
    addgtype,
    getgoodtypes,
    addgood,
    upload,
    getallgoods,
    getgoodinfo
};